--
-- Created by IntelliJ IDEA.
-- User: galileoliu
-- Date: 2018/8/29
-- Time: 15:31
-- Copyright (c) 2018      Figure Inc.
--

local ClassRef = app.mvc.createRenderClass(...)

local GAP = 10

function ClassRef.createWithData(content, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.GuideTipNode))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(content)
    return sprite
end

-- data = Guide
function ClassRef:init(content)
    self.super.init(self, content)

    self._ui.Panel:setTouchEnabled(false)

    self._textSize = self._ui.Text:getContentSize()
    self._panelSize = self._ui.Panel:getContentSize()
    self._timeline = self:getTimeline()

    self:refresh(content)
end

function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

function ClassRef:show()
    self:setVisible(true)
    self._timeline:gotoFrameAndPlay(0, false)
end

function ClassRef:hide()
    self:setVisible(false)
    self._timeline:pause()
end

function ClassRef:refresh(content)
    if content then
        -- desc
        self._ui.Text:setTextAreaSize(cc.size(self._textSize.width, 0))
        self._ui.Text:setString(content)

        local size = self._ui.Text:getVirtualRendererSize()
        local dis = size.height - self._textSize.height
        if dis > 0 then
            self._ui.Panel:setContentSize(cc.size(self._panelSize.width, self._panelSize.height + dis))
        else
            self._ui.Panel:setContentSize(self._panelSize)
        end
        ccui.Helper:doLayout(self._ui.Panel)

        -- tip pos
        self._ui.Panel:setPositionY(100)

        -- avoid out screen
        local worldPos = self:convertToWorldSpace(cc.p(0,0))
        local dis = 0
        if worldPos.x < (self._panelSize.width / 2 + GAP) then
            dis = self._panelSize.width / 2 + GAP - worldPos.x
        elseif worldPos.x > (display.width - self._panelSize.width / 2 - GAP) then
            dis = (display.width - self._panelSize.width / 2 - GAP) - worldPos.x
        end
        self._ui.Panel:setPositionX(dis)
        self._ui.arrow:setPositionX(self._panelSize.width / 2 - dis)
    end
end

return ClassRef